package com.exonline.back.controller.manager;

import cn.hutool.core.util.IdUtil;
import com.exonline.commons.entity.Teacher;
import com.exonline.commons.base.IBaseServlet;
import com.exonline.commons.utils.SqlConditionBuilder;
import com.exonline.commons.utils.TokenUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc 管理员模块c层
 * @author hbrj
 */
@WebServlet("/admin/manager")
public class ManagerServlet extends HttpServlet implements IBaseServlet {
    ObjectMapper mapper = new ObjectMapper();
    ManagerService service = new ManagerService();
    int pageno = 1;
    int pagesize = 4;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      if (req.getParameter("pageno") != null){
          pageno = Integer.parseInt(req.getParameter("pageno"));
      }
        {
            String method = req.getParameter("method");
            try {
                //查询全部
                if ("queryall".equals(method)) {
                    queryAll(req, resp);
                    //查询一个
                } else if ("queryone".equals(method)) {
                    queryOne(req, resp);
                    //添加用户
                } else if ("add".equals(method)) {
                    add(req, resp);
                    //修改用户信息
                } else if ("edit".equals(method)) {
                    edit(req, resp);
                    //删除用户
                } else if ("delete".equals(method)) {
                    delete(req, resp);
                    //获得待审核教师列表
                } else if("getreview".equals(method)){
                    getReview(req, resp);
                    //对教师进行审核
                }else if ("doreview".equals(method)) {
                    this.executeReview(req, resp);
                    //查看待审核的指定教师的详细信息
                } else if("getreviewone".equals(method)){
                    this.getReviewOne(req, resp);
                }
            } catch (Exception e) {
                throw new ServletException("管理员模块出现错误,错误信息:"+e.getMessage(),e);
            }
        }
    }

/**
 * @desc 1.获取指定待审核教师的详细信息
 * @author hbrj
 */
    private void getReviewOne(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        try {
            String id = req.getParameter("id");
            Teacher teacher = service.queryOneReview("SELECT u.* FROM reviewteacherview u where id = ?", id);
            List<Map<String,Object>> list = service.queryAll("SELECT pictureurl FROM honorpicture h WHERE  h.tid = ? ", pagesize, pageno,id);
            teacher.setPictureurl(list);
            System.out.println("教师资质:" + list);
            Map<String, Object> map = new HashMap<>();
            map.put("code", 200);
            map.put("msg", "查询教师资质成功");
            map.put("data", teacher);
            mapper.writeValue(resp.getWriter(), map);
        }catch (Exception e){
            throw new RuntimeException("获取教师审核详细信息出现错误:" + e.getMessage(), e);
        }

    }

    /**
     * @desc 2.对指定教师进行审核操作
     * @author hbrj
     */
    private void executeReview(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        try {
            String aid = TokenUtils.getId(req);
            String id = IdUtil.simpleUUID();
            String tid = req.getParameter("id");
            String comment = "";
            if (req.getParameter("comment") != null && !req.getParameter("comment").equals("")) {
                comment = req.getParameter("comment");
            }
            String status = req.getParameter("status");
            service.executeReview(id,tid,aid,comment,status);
            Map<String, Object> map = new HashMap<>();
            map.put("code", 200);
            map.put("msg", "老师审核成功");
            map.put("data", id);
            mapper.writeValue(resp.getWriter(), map);
        }catch (SQLException | IOException e) {
            throw new SQLException("教师审核模块错误:" + e.getMessage() + e);
        }
    }
/**
 * @desc 3.获取当前全部待审核教师
 * @author hbrj
 */
    private void getReview(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        try {
            if (req.getParameter("name") != null) {
                String name = req.getParameter("name")+"%";
                List<Teacher> teachers = service.queryAllReview("SELECT * FROM reviewteacherview WHERE tname like ?",pagesize, pageno,name);
                Map<String, Object> statusInfo = service.getStatusInfo();
                Map<String, Object> map = new HashMap<>();
                map.put("code", 200);
                map.put("msg", "待审核教师查询成功");
                map.put("data", teachers);
                map.put("statusinfo", statusInfo);
                mapper.writeValue(resp.getWriter(), map);
            }else {
                List<Teacher> teachers = service.queryAllReview(pagesize, pageno);
                Map<String, Object> map = new HashMap<>();
                Map<String, Object> statusInfo = service.getStatusInfo();
                String rowCount = service.getRowCount("SELECT COUNT(*) from teacher where status = 0");
                map.put("code", 200);
                map.put("msg", "待审核教师查询成功");
                map.put("data", teachers);
                map.put("statusinfo", statusInfo);
                map.put("rowCount", rowCount);
                mapper.writeValue(resp.getWriter(), map);
            }
        } catch (SQLException | IOException e) {
            throw new SQLException("数据库查询待审核教师失败" + e.getMessage(), e);
        }
    }

    /**
     * @desc 4.查询全部用户,可使用状态和角色作为条件
     * @author hbrj
     */
    private void queryAll(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if (req.getParameter("condition") != null) {
                String sql = SqlConditionBuilder.buildUserQueryFullSqlCondition(req);
                List list = service.queryAll(sql, pagesize, pageno);
                String rowCount = service.getRowCount("SELECT COUNT(*) from userview");
                Map<String, Object> map = new HashMap<>();
                map.put("code", 200);
                map.put("msg", "查询成功");
                map.put("data", list);
                map.put("rowcount", rowCount);
                mapper.writeValue(resp.getWriter(), map);
            }else {
                List list = service.queryAll(pagesize, pageno);
                String rowCount = service.getRowCount("SELECT COUNT(*) from userview");
                Map<String, Object> map = new HashMap<>();
                map.put("code", 200);
                map.put("msg", "查询成功");
                map.put("data", list);
                map.put("rowCount", rowCount);
                mapper.writeValue(resp.getWriter(), map);
            }
        } catch (RuntimeException | IOException | SQLException e) {
            throw new RuntimeException("管理员模块出现错误,错误信息:"+e.getMessage(),e);
        }
    }
    /**
     * @desc 5.管理员删除指定用户,按照id删除
     * @author hbrj
     */
    @Override
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String id = req.getParameter("id");
        service.deleteById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "查询成功");
        map.put("data", id);
        mapper.writeValue(resp.getWriter(), map);
    }
    /**
     * @desc 6.管理员查询一个用户,id精确查询或name右模糊
     * @author hbrj
     */
    @Override
    public void queryOne(HttpServletRequest req, HttpServletResponse resp)  {
        String id = "";
        String name = "";
        try {
            if (req.getHeader("Authorization") != null) {
            id = TokenUtils.getId(req);
            List<Map<String, Object>> stringMap = (List<Map<String, Object>>) service.queryOne(id);
            Map<String, Object> map = new HashMap<>();
            map.put("code", 200);
            map.put("msg", "查询成功");
            map.put("data", stringMap);
            mapper.writeValue(resp.getWriter(), map);
            return;
        }
            if (req.getParameter("id") != null) {
                id = req.getParameter("id");
                List<Map<String, Object>> stringMap = (List<Map<String, Object>>) service.queryOne(id);
                Map<String, Object> map = new HashMap<>();
                map.put("code", 200);
                map.put("msg", "查询成功");
                map.put("data", stringMap);
                mapper.writeValue(resp.getWriter(), map);
            }else if(req.getParameter("name") != null) {
                name = req.getParameter("name");
                List<Map<String, Object>> stringMap = (List<Map<String, Object>>) service.queryOne(name);
                Map<String, Object> map = new HashMap<>();
                map.put("code", 200);
                map.put("msg", "查询成功");
                map.put("data", stringMap);
                mapper.writeValue(resp.getWriter(), map);
            }
        } catch (SQLException | IOException e) {
            throw new RuntimeException("查询单个用户时出现错误,请确认参数内容包含 id 或 name!"+e.getMessage(),e);
        }
    }
    /**
     * @desc 7.编辑管理员信息
     * @author hbrj
     */
    @Override
    public void edit(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String id = "";
        Map userMap = mapper.readValue(req.getInputStream(), Map.class);

        if (req.getHeader("Authorization") != null) {
             id = TokenUtils.getId(req);
        }else {
             Map<String, Object> map = new HashMap<>();
                     map.put("code", 201);
                     map.put("msg", "修改信息失败,请确认是否包含鉴权信息");
                     map.put("data", id);
                     mapper.writeValue(resp.getWriter(), map);
                     return;
        }

        String name = userMap.get("name").toString();
        String phone = userMap.get("phone").toString();
        String email = userMap.get("email").toString();
        service.update(name,phone,email,id);
         Map<String, Object> map = new HashMap<>();
                 map.put("code", 200);
                 map.put("msg", "修改个人信息成功");
                 map.put("data", id);
                 mapper.writeValue(resp.getWriter(), map);
    }
    /**
     * @desc 7.添加用户,按三种角色,老师,学生,管理员
     * @author hbrj
     */
    @Override
    public void add(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        service.addUser(req,resp);
    }
}
